import SparkMD5 from 'spark-md5'

export function createChunk(file, index, chunkSize, chunkCount) {
    return new Promise(resolve => {
        const start = index * chunkSize
        const end = start + chunkSize
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()
        const blob = file.slice(start, end)
        fileReader.onload = e => {
            spark.append(e.target.result)
            // 为每个切片创建md5，然后把文件的md5也返回
            const result = {
                start,
                end,
                index,
                hash: spark.end().toUpperCase(),
                // hash: SparkMD5.ArrayBuffer.hash(e.target.result).toUpperCase(),
                blob,
                result: e.target.result
            }
            resolve(result)
        }
        fileReader.readAsArrayBuffer(blob)
    })
}

export const getFileMD5 = file => {
    return new Promise((resolve, reject) => {
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()
        fileReader.onload = e => {
            spark.append(e.target.result)
            resolve(spark.end().toUpperCase())
        }
        fileReader.onerror = () => {
            reject('')
        }
        fileReader.readAsArrayBuffer(file)
    })
}
